﻿using furion.blog.Domain.Shared;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Domain.Query.Feedback
{
    public class FeedbackListQuery : BaseQuery
    {

        public string SearchContent { get; set; } = string.Empty;
        public string IsDelete { get; set; } = string.Empty;

        private string Columns = " m.member_id as `MemberId`, m.real_name as `RealName`," +
            "m.nick_name as `NickName`,m.phone as `Phone`,m.sex as `Sex`," +
            "m.birthday as `Birthday`,m.created_time as `RegisterTime`,t.feedback_id as `FeedbackId`" +
            ",t.created_time as `CreatedTime` ,t.content as `Content` " +
            "  ";

        private string Tables()
        {
            return " feedback t " +
                " inner join member m on m.member_id=t.member_id ";
        }

        public string GetCountSQL()
        {
            var (strWhere, sqlParams) = QueryParams();
            return " select count(t.FeedbackId) from (select "+Columns+" from "+Tables()+" where 1=1 "+strWhere+" ) t ";
        }

        public string GetDataSQL()
        {
            var (strWhere, sqlParams) = QueryParams();
            return " select " + Columns + " from " + Tables() + 
                " where t.created_time<=(select t.created_time from " + Tables() + " where 1=1 " + strWhere + " order by t.created_time desc limit " + GetStartIndex() + ",1 ) " +
                " " + strWhere + " order by t.created_time desc limit " + PageSize;
        }


        /// <summary>
        /// 返回查询where 和 条件参数
        /// </summary>
        /// <returns></returns>
        public (string, List<SugarParameter>) QueryParams()
        {
            List<SugarParameter> parameters = new List<SugarParameter>();
            StringBuilder strWhere = new StringBuilder(" ");

            if (!string.IsNullOrWhiteSpace(SearchContent)) {
                strWhere.AppendLine(" and (m.phone like @searchContent " +
                     " or m.real_name like @searchContent " +
                     " or m.nick_name like @searchContent " +
                     " or m.email like @searchContent " +
                     " or t.content like @searchContent " +
                     ") ");
                parameters.Add(new SugarParameter("searchContent", "%"+ SearchContent + "%"));
            }
            if (!string.IsNullOrWhiteSpace(IsDelete)) {
                strWhere.AppendLine(" and t.is_delete=@isDelete ");
                parameters.Add(new SugarParameter("isDelete",IsDelete));
            }

            return (strWhere.ToString(), parameters);
        }
    }
}